Reverse Linked List

Reverse a singly linked list.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

Solution:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode reverseList(ListNode head) {
  11. if (head == null)
  12. return null;
  13. ListNode prev = null, curr = head, next = null;
  14. while (curr != null) {
  15. next = curr.next;
  16. curr.next = prev;
  17. prev = curr;
  18. curr = next;
  19. }
  20. return prev;
  21. }
  22. }